﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections;
using System.Text;
using Portal.Environment;
using Portal.Language;
using Portal.Interface;
using System.IO;

namespace Portal.CDSP
{
    public class FAskQuestionsFWP : WebPart
    {
        class PersonalizationCls
        {
            public int MaxItem = 4;
            public PersonalizationCls()
            {
            }
            public PersonalizationCls(int _MaxItem)
            {
                MaxItem = _MaxItem;
            }
        }
        public override string WebPartId
        {
            get
            {
                return "WebSite.FAskQuestionsFWP";
            }
        }

        public override string WebPartFolder
        {
            get
            {
                return "Portal.CDSP";
            }
        }


        public override string Title
        {
            get
            {
                return GetText("Title", "CĐSPNA-Chuyên mục hỏi đáp");
            }
        }

        public override ViewCls[] Views
        {
            get
            {
                return new ViewCls[]{
                     new ViewCls("DefaultView",GetText("default","Kiểu ngầm định"),1)
                };
            }
        }


        [AjaxPro.AjaxMethod]
        public override string ClientRenderWebPart(string BelongSite, string TabModuleId, string ViewName, string HasPorlet, LoadParamCls loadParamCls)
        {
            return RenderAfterPersonalization(TabModuleId, ViewName);
        }

        [AjaxPro.AjaxMethod]
        public string RenderAfterPersonalization(string TabModuleId, string ViewName)
        {
            try
            {
                string FunctionId = TabModuleId.Replace("-", "");
                FunctionId = FunctionId.Replace("_", "");

                if (ViewName.Equals("DefaultView"))
                {
                    return
                        ClientRenderWebPart(TabModuleId, "0");
                }
                return GetText("ViewNotFound", "Không tìm thấy View [" + ViewName + "]");
            }
            catch (Exception ex)
            {
                return ex.Message.ToString();
            }
        }


        public override DataTable ReadingDataService(string belongSite, string ActiveLanguage, ref string IdField, ref string SubjectField)
        {
            IdField = "Id";
            SubjectField = "Subject";
            DataTable dtResult = new DataTable();
            dtResult.Columns.Add("Id");
            dtResult.Columns.Add("Subject");
            dtResult.Rows.Add(new object[]{
                "69EB07FC-EA01-46fe-A1B3-5BDA611C7979","Chuyên mục hỏi đáp"
            });
            return dtResult;
        }


        private string ClientRenderWebPart(string TabModuleId, string HasPorlet)
        {
            AjaxPro.Utility.RegisterTypeForAjax(typeof(Portal.CDSP.FAskQuestionsFWP));
            TabModuleCls TabModuleCls = new TabModuleBLL().CreateModelFromXml(TabModuleId);
            int Top = 5;
            DataTable dtItem = new FAskQuestionsBLL().ReadingForShow(Top);
            //doan này làm cá nhân hóa
            int MaxItem = dtItem.Rows.Count;
            PersonalizationCls oPersonalizationCls = null;
            oPersonalizationCls = GetPersonalizationCls(TabModuleId);
            if (oPersonalizationCls != null)
            {
                MaxItem = oPersonalizationCls.MaxItem;
                if (MaxItem > dtItem.Rows.Count)
                {
                    MaxItem = dtItem.Rows.Count;
                }
            }
            try
            {
                string html = WebPartUtilities.AttachJavascript(WebPartFolder, "Questions.js") +
                    "<div class=\"leftcolheader\">      " +
                    "<h3><a href=\"#\">HỎI-ĐÁP</a></h3>            " +
                    "</div>" +
                "  <div class=\"boxContent\">";
                for (int iNews = 0; iNews < MaxItem; iNews++)
                {
                    string ShortId = (string)dtItem.Rows[iNews]["ShortId"];

                    string Subject = "";
                    try
                    {
                        Subject = (string)dtItem.Rows[iNews]["AskContent"];
                    }
                    catch { }

                    DateTime EntryDate = DateTime.Now;
                    try
                    {
                        EntryDate = (DateTime)dtItem.Rows[iNews]["AskTime"];
                    }
                    catch { EntryDate = DateTime.Now; }

                    int AskTotalClick = 0;
                    try
                    {
                        AskTotalClick = (int)dtItem.Rows[iNews]["AskTotalClick"];
                    }
                    catch { AskTotalClick = 0; }

                    string AskAnswer = string.Empty;
                    try
                    {
                        AskAnswer = (string)dtItem.Rows[iNews]["AskAnswer"];
                    }
                    catch { AskAnswer = string.Empty; }

                    AskAnswer = Ultility.SplitContent(AskAnswer);

                    string Url = Environments.GetNewsUrl(TabModuleCls.belongSite, ShortId, Subject, "_runtime");
                    Url = new FAskQuestionsBLL().RewriteGetByCategoryUrl(Url);
                    html +=
                        "<h4><a href=\"" + Url + "\">" + Subject + "</a></h4>" +
                        "<span><i><b>Trả lời:</b>" +
                        AskAnswer +
                        "</span><a href=\"" + Url + "\">(Xem thêm)</a></i><br><br>";                        
                }
                html +=
                    "<div class = \"faqsubmit\">" +
                    "<a onclick=\"javascript:ShowForm('" + TabModuleCls.belongSite + "');\">" + GetText("SentNewQuestions", "Gửi câu hỏi") + "</a>" +
                    "</div>" +                    
                    "</div>" +                    
                    "<div class=colfix></div>";

                return html;
            }
            catch (Exception ex)
            {
                return "ERROR:" + ex.Message;
            }
        }

        [AjaxPro.AjaxMethod]
        public string ServerSideInsertQuestion(string AskContent, string AskBy, string Email, string belongSite)
        {
            try
            {
                //string Ret = new FAskQuestionsBLL().InsertFAQ(null, AskContent, AskBy, Email, belongSite);
                DateTime dateAsk = DateTime.Now;
                string AskAnswer = string.Empty;
                string Ret = new FAskQuestionsBLL().ServerSideInsertFAQ(null, belongSite, belongSite, AskContent, AskBy, Email, dateAsk, AskAnswer, false);
                if (Ret == null)
                    return GetText("ErrorSendFeedback", "ERROR:Câu hỏi không gửi được, xin vui lòng quay lại sau!");
                else
                    return GetText("OKSendQuestions", "Câu hỏi đã được gửi thành công,cảm ơn bạn!");
            }
            catch (Exception ex)
            {
                return "ERROR: " + ex.Message;
            }
        }

        public override bool AllowFrontService
        {
            get
            {
                return true;
            }
        }

        /// ************ CÁ NHÂN HÓA ******************
        public override bool AllowPersonalization
        {
            get
            {
                return true;
            }
        }

        [AjaxPro.AjaxMethod]
        public string SavePersonalzationContent(string TabModuleId, string MaxNews)
        {
            try
            {
                DataSet ds = new DataSet();
                ds.Tables.Add("Config");
                ds.Tables[0].Columns.Add("MaxNews");
                ds.Tables[0].Rows.Add(new object[]{
                    MaxNews
                });


                string XmlData = ds.GetXml();
                PersonalizationBll.SavePersonalization(TabModuleId, XmlData);
                return PersonalizationBll.GetSaveOkMsg();
            }
            catch (Exception ex)
            {
                return "ERROR: " + ex.Message.ToString();
            }
        }

        public override string PersonalizationPlugInJavascripts(string TabModuleId)
        {
            string FunctionId = TabModuleId.Replace("-", "");
            FunctionId = FunctionId.Replace("_", "");
            return
                    "<script type=\"text/javascript\">\r\n" +
                    "      function SaveAskQuestion" + FunctionId + "(WebPartId,TabModuleId)\r\n" +
                    "      {\r\n" +
                    "          MaxNews=document.getElementById(\"txtMaxNews" + FunctionId + "\").value;\r\n" +
                    "          rValue=Portal.CDSP.FAskQuestionsFWP.SavePersonalzationContent(TabModuleId,MaxNews).value;\r\n" +
                               PersonalizationBll.GetJavascriptCloseForm(this, TabModuleId) + "\r\n" +
                    "      }\r\n" +
                    "</script>";
        }


        PersonalizationCls GetPersonalizationCls(string TabModuleId)
        {
            string XmlData = PersonalizationBll.GetPersonalizationData(TabModuleId);
            string MaxNews = "4";

            if (XmlData.Trim().Length > 0)
            {
                DataSet ds = new DataSet();
                ds.ReadXml(new StringReader(XmlData));
                MaxNews = (string)ds.Tables[0].Rows[0]["MaxNews"];
                PersonalizationCls PersonalizationCls = new PersonalizationCls(int.Parse(MaxNews));
                return PersonalizationCls;
            }
            return null;
        }

        public override string GetPersonalizationConfig(
            LoadParamCls loadParamCls,
            string TabModuleId)
        {
            try
            {
                string FunctionId = TabModuleId.Replace("-", "");
                FunctionId = FunctionId.Replace("_", "");
                string XmlData = PersonalizationBll.GetPersonalizationData(TabModuleId);
                string MaxNews = "4";

                if (XmlData.Trim().Length > 0)
                {
                    DataSet ds = new DataSet();
                    ds.ReadXml(new StringReader(XmlData));
                    MaxNews = (string)ds.Tables[0].Rows[0]["MaxNews"];
                }
                return "<div>" +
                       "        <table>" +
                       "            <tr>" +
                       "                <td>Số tin hiện</td>" +
                       "            </tr>" +
                       "            <tr>" +
                       "                <td><input id=\"txtMaxNews" + FunctionId + "\" value=\"" + MaxNews + "\"></td>" +
                       "            </tr>" +
                       "            <tr>" +
                       "                <td><input onclick=\"javascript:" + "SaveAskQuestion" + FunctionId + "('" + WebPartId + "','" + TabModuleId + "');\" type=button value=\"Ghi lại\"><input type=button value=\"Hủy bỏ\" onclick=\"" + PersonalizationBll.GetJavascriptExitPersonalization(this, TabModuleId) + "\"></td>" +
                       "            </tr>" +
                       "        </table>" +
                       "</div>";
            }
            catch (Exception ex)
            {
                return "ERROR: " + ex.Message.ToString();
            }
        }

        [AjaxPro.AjaxMethod]
        public string ServerSideRenderQuickSent(string belongSite)
        {
            string Html = string.Empty;
            Html += "<p><a onclick=\"javascript:$.modal.close();\" class='closeDialog'><span>Đóng<span></a></p>" +

            "  <div id=\"contactLink\" align=\"right\"><a>" + GetText("CmsNewQuestion1", "Gửi câu hỏi") + "</a></div>" +
            "   <div id=\"contactFormContainer\">" +
            "    <div id=\"contactForm\">" +
            "        <fieldset>" +
            "            <label for=\"Name\">" + GetText("FAQCustomerNameRequire", "Họ tên (*)") + "</label>" +
            "            <input id=\"Name\" type=\"text\" value=\"\"/>" +
            "            <label for=\"Email\">" + GetText("FAQCustomerEmailRequire", "Email (*)") + "</label>" +
            "            <input id=\"Email\" type=\"text\" value=\"\"/>" +
            "           <label for=\"Message\">" + GetText("FAQCustomerMessageRequire", "Câu hỏi (*)") + "</label>" +
            "            <textarea id=\"Message\" rows=\"4\" cols=\"20\"></textarea><br>" +
            "            <input id=\"sendMail\" type=\"button\" name=\"Submit\" value=\"" + GetText("FAQCustomerSentQuestion", "Gửi câu hỏi") + "\" onclick=\"ClientHomeSaveAddNewQuession('" + belongSite + "')\" />\r\n" +
            "            <input id=\"Exit\" type=\"button\" name=\"Exit\" value=\"" + GetText("FQACustomerExit", "Thoát") + "\" onclick=\"javascript:$.modal.close();\" />" +
            "       </fieldset>" +
            "    </div>" +
            "</div>";

            Html += "<p><a onclick=\"javascript:$.modal.close();\" class='closeDialog'><span>Đóng<span></a></p>";

            return Html;
        }


        public override void RegAjaxPro(System.Web.UI.Page ActivePage)
        {
            AjaxPro.Utility.RegisterTypeForAjax(typeof(Portal.CDSP.FAskQuestionsFWP), ActivePage);
        }

    }
}
